<template>
  <div class="title">人口分布</div>
  <div class="chartbox" ref="chartRef"> </div>
</template>  
  
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null);
let myChart = null;

// 初始化图表
const initChart = (option) => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value)

    const PublicChartOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        top: 40,
        right: 20,
        left: 50,
        bottom: 40
      },
      xAxis: {
        type: 'category',
        data: ['5公里', '10公里', '20公里', '50公里', '100公里'],
        axisLine: {
          lineStyle: {
            color: '#B9EEFF'
          }
        },
        axisTick: { show: false },
        axisLabel: {
          margin: 10,
          color: '#B9EEFF',
          textStyle: {
            fontSize: 14,
            color: '#B9EEFF'
          }
        }
      },
      yAxis: {
        name: '万人',
        axisLabel: {
          formatter: '{value}',
          color: '#B9EEFF'
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#fff'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255,255,255,0.12)'
          }
        }
      },
      series: {
        type: 'bar',
        data: [1.08, 2.34, 3.2, 20, 100],
        barWidth: '20px',
        itemStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0,
                  color: ' #01C2FF ' // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: 'rgba(0,77,167,1)' // 100% 处的颜色
                }
              ],
              false
            ),
            barBorderRadius: [30, 30, 0, 0],
            shadowColor: 'rgba(1, 194, 255, 0)'
          }
        },
        label: {
          show: true,
          position: 'top', // 在柱状图的上方显示文字
          textStyle: {
            color: '#B9EEFF' // 文字颜色为黑色
          }
        }
      }
    }

    myChart.setOption(PublicChartOption)
    // 指定图表的配置项和数据
  }
}

const getData = (e) => {
  initChart(e)
}
// 主动暴露childMethod方法
defineExpose({ getData })


// 组件挂载后初始化图表
onMounted(() => {
  initChart()
  window.addEventListener('resize', () => {
    myChart && myChart.resize()
  })
})

// 组件卸载时销毁图表实例，避免内存泄漏
onUnmounted(() => {
  if (myChart) {
    myChart.dispose()
  }
})
</script>  
  
<style scoped>
.title {
  height: 41px;
  color: #fff;
  line-height: 41px;
  font-size: 18px;
  padding-left: 26px;
  font-weight: bold;
}
.chartbox {
  height: calc(100% - 41px);
}
</style>